import type { ExecutionContext } from '@nestjs/common'
// 全局守卫
import { Injectable, UnauthorizedException } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { AuthGuard } from '@nestjs/passport'

import { JwtTool } from '@/shared/utils/tool'

@Injectable()
export class JwtGuard extends AuthGuard('jwt') {
  private jwt = new JwtTool()

  constructor(private reflector: Reflector) {
    super()
  }

  canActivate(context: ExecutionContext): boolean {
    const JwtNeed = this.reflector.getAllAndOverride<boolean>('JwtNeed', [context.getHandler(), context.getClass()])
    if (!JwtNeed)
      return true
    const request = context.switchToHttp().getRequest()
    const token = this.extractTokenFromHeader(request)
    try {
      // const isPass = this.reflector.get<boolean>('jwtPass', context.getHandler())
      // if (isPass)
      // return true

      // 获取前缀web
      // const prefix = request.url.split('/')[2]
      // if (prefix === 'web')
      //   return true
      if (!token) {
        throw new UnauthorizedException('请登录')
        // throw new (request as any).customException('请登录', 401);
      }

      const decoded = this.jwt.verifyToken(token)

      request.user = decoded

      return true
    }
    catch {
      throw new UnauthorizedException('无效 token')
    }
  }

  private extractTokenFromHeader(request: any): string | undefined {
    const authorization = request.headers.authorization ?? ''
    const token = authorization.trim().replace(/Bearer\s+/i, '')
    return authorization ? token : undefined
  }
}

/**
 * @UseGuards()  // 不使用守卫，允许访问
 * @UseGuards(LocalAuthGuard) // 仅对这个路由使用本地认证，绕过 JWT 验证
 */
